package com.buercorp.wangyu.core1.ch12.threads;

/**
 * ThreadLocal是Java中一个用于实现线程本地存储的类。
 * 它允许每个线程都拥有自己的变量副本，从而实现线程之间的数据隔离。
 * @author liyiyu
 */
public class ThreadLocalExample {
    private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        // 在主线程中设置threadLocal的值
        threadLocal.set(10);
        System.out.println("Main thread: " + threadLocal.get());

        // 创建一个新的子线程并启动
        Thread thread = new Thread(() -> {
            // 在子线程中设置threadLocal的值
            threadLocal.set(20);
            System.out.println("Child thread: " + threadLocal.get());
        });
        thread.start();

        // 等待子线程执行完毕
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 在主线程中获取threadLocal的值
        System.out.println("Main thread after child thread: " + threadLocal.get());
    }
}

